import React from 'react';
import { Card, Table, Button, Input, Modal, Form, Space, message, Popconfirm } from 'antd';

// 商品标签（模仿 admin-web 的 ProductTag.vue）
export default function ProductTag() {
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '' });
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  const [list, setList] = React.useState(() => ([
    { id: 1, name: '热销', notes: '高销量商品标签', createTime: '2025-09-10 09:20' },
    { id: 2, name: '新品', notes: '新上架商品标签', createTime: '2025-09-12 15:30' },
    { id: 3, name: '限时', notes: '限时优惠标签', createTime: '2025-09-15 21:45' },
  ]));

  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [form] = Form.useForm();

  const filtered = React.useMemo(() => {
    let data = list;
    if (search.name) data = data.filter(i => String(i.name).includes(search.name));
    return data;
  }, [list, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  const columns = [
    { title: '标签名称', dataIndex: 'name', align: 'center' },
    { title: '备注', dataIndex: 'notes' },
    { title: '创建时间', dataIndex: 'createTime', width: 160, align: 'center' },
    {
      title: '操作',
      fixed: 'right',
      width: 160,
      align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => editProductTag(row)}>编辑</Button>
          <Popconfirm title={`确认删除标签“${row.name}”吗？`} onConfirm={() => delProductTag(row)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const onResetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '' });
    setPageIndex(1);
  };

  const addProductTag = () => {
    setEditing(null);
    form.resetFields();
    setDialogOpen(true);
  };
  const editProductTag = (row) => {
    setEditing(row);
    form.setFieldsValue({ name: row.name, notes: row.notes });
    setDialogOpen(true);
  };
  const onSave = async () => {
    const values = await form.validateFields();
    if (editing) {
      setList(prev => prev.map(i => i.id === editing.id ? { ...i, ...values } : i));
      message.success('商品标签已更新');
    } else {
      const maxId = Math.max(0, ...list.map(i => i.id));
      setList(prev => [{ id: maxId + 1, createTime: new Date().toLocaleString(), ...values }, ...prev]);
      message.success('商品标签已新增');
    }
    setDialogOpen(false);
  };
  const delProductTag = (row) => {
    setList(prev => prev.filter(i => i.id !== row.id));
    message.success('删除成功');
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Card variant="borderless">
        <Form form={searchForm} layout="inline" initialValues={search} style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Form.Item name="name" label="标签名称">
            <Input allowClear placeholder="请输入标签名称" style={{ width: 220 }} />
          </Form.Item>
          <Space>
            <Button type="primary" onClick={onSearchSubmit}>查询</Button>
            <Button onClick={onResetSearch}>重置</Button>
            <Button type="dashed" onClick={addProductTag}>新增标签</Button>
          </Space>
        </Form>
      </Card>

      <Card title="商品标签清单" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => { setPageIndex(pi); setPageSize(ps); },
          }}
        />
      </Card>

      <Modal title={editing ? '编辑商品标签' : '新增商品标签'} open={dialogOpen} onOk={onSave} onCancel={() => setDialogOpen(false)}>
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="标签名称" rules={[{ required: true, message: '请输入标签名称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="notes" label="备注"> 
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}